package com.intretech.umsin.common.exception;

import com.intretech.umsin.common.web.ApiResult;
import com.intretech.umsin.common.web.ResultCode;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @version V1.0
 * @ClassName: ControllerExceptionAdvice
 * @Description: 功能描述 统一异常处理
 * @author: 李启联
 * @date: 2022-7-15 13:56
 * @Copyright: Copyright (c) 2022
 */
@RestControllerAdvice
public class ControllerExceptionAdvice {

    @ExceptionHandler({BindException.class})
    public ApiResult MethodArgumentNotValidExceptionHandler(BindException e){

        //从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ApiResult<>(ResultCode.VALIDATE_ERROR.getCode(),ResultCode.VALIDATE_ERROR.getMsg(),objectError.getDefaultMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ApiResult BusinessExceptionHandler(BusinessException e) {
        return new ApiResult<>(ResultCode.FAILED.getCode(), e.getMessage());
    }


}